﻿using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class ProjectileMover : MonoBehaviour
{
    public Vector3 target;                 // 目标位置（地面红圈位置）
    public float flightDuration = 1.5f;   // 飞行时间
    public float gravity = -9.81f;        // 模拟重力（一般为负值）

    private Rigidbody rb;

    public float speed = 15f;
    public float hitOffset = 0f;
    public bool UseFirePointRotation;
    public Vector3 rotationOffset = new Vector3(0, 0, 0);
    public GameObject hit;
    public GameObject flash;
    public GameObject[] Detached;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.useGravity = false; // 我们自己模拟重力，不使用Unity的内建重力

        Launch();
    }

    void Launch()
    {
        Vector3 startPos = transform.position;
        Vector3 endPos = target;

        // 水平方向速度
        Vector3 toTarget = endPos - startPos;
        Vector3 toTargetXZ = new Vector3(toTarget.x, 0f, toTarget.z);
        float distanceXZ = toTargetXZ.magnitude;

        float vxz = distanceXZ / flightDuration;
        Vector3 velocityXZ = toTargetXZ.normalized * vxz;

        // 垂直方向初速度计算（使用匀加速公式：v0y = (dy - 0.5 * g * t^2) / t）
        float dy = endPos.y - startPos.y;
        float vy = (dy - 0.5f * gravity * flightDuration * flightDuration) / flightDuration;

        // 合成最终速度向量
        Vector3 launchVelocity = velocityXZ + Vector3.up * vy;

        rb.velocity = launchVelocity;
    }

    void FixedUpdate()
    {
        // 模拟重力
        rb.velocity += Vector3.up * gravity * Time.fixedDeltaTime;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player") || other.CompareTag("Ground"))
        {
            rb.constraints = RigidbodyConstraints.FreezeAll;
            speed = 0;

            Vector3 contactPoint = transform.position;
            Vector3 contactNormal = -rb.velocity.normalized; // 用速度方向的反方向近似法线
            Quaternion rot = Quaternion.FromToRotation(Vector3.up, contactNormal);
            Vector3 pos = contactPoint + contactNormal * hitOffset;

            if (hit != null)
            {
                var hitInstance = Instantiate(hit, pos, rot);
                if (UseFirePointRotation)
                {
                    hitInstance.transform.rotation = transform.rotation * Quaternion.Euler(0, 180f, 0);
                }
                else if (rotationOffset != Vector3.zero)
                {
                    hitInstance.transform.rotation = Quaternion.Euler(rotationOffset);
                }
                else
                {
                    hitInstance.transform.LookAt(contactPoint + contactNormal);
                }

                var hitPs = hitInstance.GetComponent<ParticleSystem>();
                if (hitPs != null)
                {
                    Destroy(hitInstance, hitPs.main.duration);
                }
                else
                {
                    var hitPsParts = hitInstance.transform.GetChild(0).GetComponent<ParticleSystem>();
                    Destroy(hitInstance, hitPsParts.main.duration);
                }
            }

            foreach (var detachedPrefab in Detached)
            {
                if (detachedPrefab != null)
                {
                    detachedPrefab.transform.parent = null;
                }
            }

            Destroy(gameObject);
        }
    }
}
